package yunhe.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import yunhe.biz.StockMgrBiz;
import yunhe.biz.impl.StockMgrBizImpl;
import yunhe.entity.EmpMsg;
import yunhe.entity.Product;
import yunhe.entity.Purchase;
import yunhe.entity.StockIn;
import yunhe.entity.StockInAppend;
import yunhe.util.GeneralUtil;

@WebServlet(name = "InStockServlet",urlPatterns = "/InStockServlet")

public class InStockServlet extends HttpServlet
{
/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException
{
	doPost(req,resp);
}
@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
	  StockMgrBiz smb=new StockMgrBizImpl();
	  String pursId=request.getParameter("pursId");

	  String stokid=GeneralUtil.creatSeq("SI");
      String empMsg=request.getParameter("empMsg");
      String stockReason=request.getParameter("stockReason");
      
      
      StockIn si=new StockIn();
      si.setStockInReason(stockReason);
      EmpMsg e=new EmpMsg();
      e.setWorkId(empMsg);
      si.setEmpMsg(e);
      si.setStockInDate(new Date(new java.util.Date().getTime()));
      si.setStockInsId(stokid);

      
      String detail=request.getParameter("detail");
      try {
          JSONArray ja=new JSONArray(detail);
          List<StockInAppend> lsoa=new ArrayList<>();
          for (int i = 0; i <ja.length() ; i++) {
        	  StockInAppend soa=new StockInAppend();
              JSONObject jo= (JSONObject) ja.get(i);
              soa.setPursId(jo.getString("InvOutOfSto"));
              soa.setStockInQuantity(jo.getInt("purQuantity"));
              soa.setStockIn(si);
              soa.setProBarCode(jo.getString("proBarCode"));
              lsoa.add(soa);
          }
          int re=smb.stockIn(si,lsoa);
          if(re>0){
              response.getWriter().print("true");
          }
          else{
              response.getWriter().print("false");
          }
      }
      catch (Exception ex) {
          ex.printStackTrace();
      }
	
	}
}
